import axios from "axios";
import { getToken, removeToken } from "@/utils/authLib";
import type { AxiosRequestConfig, AxiosResponse } from "axios";
import type { Response } from "@/mctp-api";
import router from "@/router/index";
import { ElMessage } from "element-plus";

/**
 * @description: 配置项
 */
const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  withCredentials: false, // 设置跨域cookie上传
  timeout: 180000 // 请求超时
});

/**
 * @description: request 拦截器 ==> 对请求参数做处理
 * @return {*}
 */
service.interceptors.request.use(
  (config) => {
    // 判断为下载文件
    if (config.params && config.params.isFileType) {
      config.responseType = "blob";
      config.timeout = 0;
    }
    // 设置超时时间
    if (config.params && config.params.timeout) {
      config.timeout = config.params.timeout;
    }
    // config.headers["token"] = config.headers["token"] || getToken();
    config.headers["Authorization"] = "Bearer " + (getToken() || "");
    return config;
  },
  (error) => {
    console.error(error); // for debug
    return Promise.reject(error);
  }
);
/**
 * @description: response 拦截器 ==> 对响应做处理
 * @return {*}
 */
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    return responseMethods(res) as unknown as AxiosResponse<Response<unknown>>;
  },
  (error) => {
    if (error.response.status == 401) {
      ElMessage.closeAll();
      ElMessage({
        message: "登录已过期，请重新登录",
        type: "warning",
      });
      router.push("/login");
      return Promise.reject(new Error("登录已过期，请重新登录"));
    }
    console.log("err" + error); // for debug
    return Promise.reject(error);
  }
);

/**
 * @description: 封装处理响应数据逻辑
 * @param {Response} res
 * @return {*}
 */
export function responseMethods<T>(res: Response<T>) {
  // // 当请求不为200时，报错
  if (res.code && res.code !== 200) {
    if (res.code === -406 || res.code === -407) {
      const fullPath = encodeURIComponent(router.currentRoute.value.fullPath);
      removeToken();
      console.log("res.code", res.code);
      router.push(`/login?redirect=${fullPath}`);
    }
    ElMessage.closeAll();
    ElMessage({ message: res.msg, type: "warning" });
    return Promise.reject(new Error(res.msg || "Error"));
  } else {
    return res;
  }
}
/**
 * @description: Get请求
 * @param {string} url
 * @return {*}
 */
export function createGet<P extends Record<string, any>, R>(url: string) {
  return function (params?: P, config: AxiosRequestConfig = {}): Promise<Response<R>> {
    return service.request({
      method: "get",
      url,
      params,
      ...config
    });
  };
}
export function createGetFordownload<P extends Record<string, any>, R>(url: string) {
  return function (
    params?: P,
    config: AxiosRequestConfig = {}
  ): Promise<Blob> {
    return service.request({
      method: "get",
      url,
      params,
      responseType: "blob", // 关键：告诉 Axios 不要解析 JSON，直接返回 Blob
      ...config,
    });
  };
}
/**
 * @description: Post请求
 * @param {string} url
 * @return {*}
 */
// export function createPost<P extends Record<string, any>, D = never, R = never>(url: string) {
//   return function (params?: P, data?: D, config: AxiosRequestConfig = {}): Promise<Response<R>> {
//     return service.request({
//       method: "post",
//       url,
//       data,
//       params,
//       ...config
//     });
//   };
// }
export function createPost<D extends Record<string, any>, R>(url: string, fixedParams?: any) {
  return function (data?: D, params?: any, config: AxiosRequestConfig = {}): Promise<Response<R>> {
    return service.request({
      method: "post",
      url,
      data,
      params: { ...(fixedParams || {}), ...(params || {}) },
      ...config
    });
  };
}
/**
 * @description: 创建回执
 * @return {*}
 */
export function createResponse<T>(type?: "" | "paging") {
  if (type === "paging") {
    return (data?: T) => {
      console.log("✨  Mock => ", data);
      return {
        code: 200,
        msg: "success",
        data: {
          limit: 30,
          page: 1,
          ...data
        }
      };
    };
  }
  return (data?: T) => {
    console.log("✨  Mock => ", data);
    return {
      code: 200,
      msg: "success",
      data
    };
  };
}
export default service;
